package com.beyondsoft.provider;

import java.util.ArrayList;
import java.util.List;

import com.beyondsoft.model.Book;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class DBManager {

	public static Uri CONTENT_URI = Uri.parse("content://com.beyondsoft/books");
	public static String[] argments = new String[1];
	public static String SELECTION;
	static {
		StringBuilder buffer = new StringBuilder();
		buffer.append("id");
		buffer.append("=?");
		SELECTION = buffer.toString();
	}

	public static Book findBookById(ContentResolver contentResolver, Integer id) {

		Book book = new Book();

		argments[0] = id + "";
		Cursor cursor = contentResolver.query(CONTENT_URI, null, SELECTION,
				argments, null);
		Log.i("sys", SELECTION + argments);
		if (cursor.moveToFirst()) {

			String _name = cursor.getString(cursor
					.getColumnIndexOrThrow("name"));
			String _author = cursor.getString(cursor
					.getColumnIndexOrThrow("author"));
			book.setId(id);
			book.setBook_name(_name);
			book.setAuthor(_author);

			return book;
		}
		return null;
	}

	public static List<Book> findAll(ContentResolver contentResolver) {

		List<Book> books = new ArrayList<Book>();
		Book book;

		Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
				null);
		if (cursor.getCount() < 1) {
			return null;
		}
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			book = new Book();
			String _id = cursor.getString(cursor.getColumnIndexOrThrow("id"));
			String _name = cursor.getString(cursor
					.getColumnIndexOrThrow("name"));
			String _author = cursor.getString(cursor
					.getColumnIndexOrThrow("author"));
			book.setId(Integer.parseInt(_id));
			book.setBook_name(_name);
			book.setAuthor(_author);
			books.add(book);
			cursor.moveToNext();
		}

		return books;
	}

	public static Uri insert(ContentResolver contentResolver, Book book) {
		ContentValues value = new ContentValues();
		value.put("name", book.getBook_name());
		value.put("author", book.getAuthor());
		Uri uri = contentResolver.insert(CONTENT_URI, value);
		return uri;
	}

	public static void update(ContentResolver contentResolver, String id) {

	}

	public static boolean delete(ContentResolver contentResolver, String id) {
		Log.i("sys", "正在删除"+id);
		int re = contentResolver.delete(CONTENT_URI, SELECTION, new String[]{id});
//		Log.i("sys", "删除结果"+re);
		return re>0;
		
	}

}
